package com.zjpavt.client.hal;

import com.zjpavt.client.nativemethod.JnIMethod;
import com.zjpavt.client.util.PropertiesUtil;

import java.io.IOException;

/**
 * 开门狗
 * @author zyc
 */
public class DogWatch {
    public static final String DOG_WATCH_USED = "dog_watch_used";
    private static final DogWatch instance = new DogWatch();

    /**
     * 是否启用开门狗（开/关）
     */
    private boolean isDogWatchUsed;
    private Thread dogWatchThread;
    private DogWatch() {
        try {
            isDogWatchUsed = Boolean.parseBoolean(PropertiesUtil.getPropertiesDefault(DOG_WATCH_USED,"true"));
            PropertiesUtil.setPropertyOrReplaceDefault(DOG_WATCH_USED,String.valueOf(isDogWatchUsed));
            dogWatchThread = new Thread(() -> {
                JnIMethod.dogWatch();
            });
            tryStartDogWatch();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static DogWatch getInstance() {
        return instance;
    }

    public boolean isDogWatchUsed() {
        return isDogWatchUsed;
    }

    /**
     * 尝试开启开门狗守护（阻塞进程）
     * 一旦开启以后 该进程不能正常运行
     * 会发生硬件重启
     */
    private void tryStartDogWatch() {
        if (isDogWatchUsed) {
            dogWatchThread.start();
        }
    }

    /**
     * 保存开门狗配置
     */
    public void saveDogWatchStatus(boolean isDogWatchUsed) {
        if (this.isDogWatchUsed != isDogWatchUsed) {
            this.isDogWatchUsed = isDogWatchUsed;
            try {
                PropertiesUtil.setPropertyOrReplaceDefault(DOG_WATCH_USED,String.valueOf(isDogWatchUsed));
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (isDogWatchUsed) {
                dogWatchThread.start();
            } else {
//              下次不再开启 本次的dog依然存在
//               System.exit(0);
            }
        }
    }
}
